<template>
  <view class="wallet-container">
    <!-- 顶部导航栏 -->
    <u-navbar :border="false" leftIcon=" " bg-color="#fff" title-color="#333" :safe-area-inset-top="true" placeholder>
      <template #center>
        <text class="navbar-title">{{ useT('钱包') }}</text>
        <!-- 顶部标签切换 -->
        <!-- <scroll-view class="tabs-scroll" scroll-x="true" :scroll-left="scrollLeft" :show-scrollbar="false">
          <view class="tabs-container">
            <view class="tab-item" :class="{ active: activeTab === 'overview' }" @click="switchTab('overview')" :id="'tab-overview'">
              <text class="tab-text">{{ useT('总览') }}</text>
            </view>
            <view class="tab-item" :class="{ active: activeTab === 'wallet' }" @click="switchTab('wallet')" :id="'tab-wallet'">
              <text class="tab-text">{{ useT('钱包') }}</text>
            </view>
            <view class="tab-item" :class="{ active: activeTab === 'wealth' }" @click="switchTab('wealth')" :id="'tab-wealth'">
              <text class="tab-text">{{ useT('理财') }}</text>
            </view>
            <view class="tab-item" :class="{ active: activeTab === 'ucard' }" @click="switchTab('ucard')" :id="'tab-ucard'">
              <text class="tab-text">{{ useT('U卡资产') }}</text>
            </view>
          </view>
        </scroll-view> -->
      </template>
    </u-navbar>

    <!-- 页面内容 -->
    <view class="content">
      <!-- 总资产估值区域 -->
      <view class="asset-section">
        <view class="asset-left">
          <view class="asset-header">
            <text class="asset-title">{{ useT('总资产估值') }}</text>
            <u-icon :name="showAmount ? 'eye' : 'eye-fill'" size="16" color="#999" @click="toggleAmountDisplay"></u-icon>
          </view>
          <view class="asset-amount-wrapper" v-if="userStore.userInfo && userStore.userInfo.now_money">
            <text class="asset-amount">{{ showAmount ? `${userStore.userInfo.now_money}USDT` : '**' }}</text>
          </view>
          <view v-else class="asset-tip">
            <text class="tip-text">{{ useT('您还没有可用资产，请先充值') }}</text>
          </view>
        </view>
        <view class="asset-right">
          <view class="recharge-btn" @click="handleRecharge">
            <text class="btn-text">{{ useT('充值') }}</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮区域 -->
      <view class="action-section">
        <view class="action-item" @click="handleWithdraw">
          <view class="action-icon">
            <u-icon name="/static/home/tx.png" size="20" color="#12C284"></u-icon>
          </view>
          <text class="action-text">{{ useT('提现') }}</text>
        </view>
        <view class="action-divider"></view>
        <view class="action-item" @click="handleRecord">
          <view class="action-icon">
            <u-icon name="/static/home/jl.png" size="20" color="#12C284"></u-icon>
          </view>
          <text class="action-text">{{ useT('记录') }}</text>
        </view>
      </view>

      <!-- 我的账户标题 -->
      <view class="account-title">
        <text class="title-text">{{ useT('我的账户') }}</text>
      </view>

      <!-- 银行卡展示 -->
      <view class="card-section">
        <!-- 有银行卡时显示 -->
        <template v-if="bankCardList.length > 0">
          <view class="bank-card" v-for="(card, index) in bankCardList" :key="card.id || index">
            <view class="card-chip">
              <image src="/static/home/xinpian.svg" class="chip-icon"></image>
            </view>
            <view class="card-number">
              <text class="number-text">{{ formatCardNumber(card.order_sn) }}</text>
            </view>
            <view class="card-extra-info">
              <view class="extra-item" style="flex: 10">
                <text class="extra-label">{{ useT('卡片状态') }}</text>
                <text class="extra-value" :class="getStatusClass(card.card_status)">{{ getStatusText(card.card_status) }}</text>
              </view>
              <view class="extra-item" style="flex: 10">
                <text class="extra-label">{{ useT('购卡日期') }}</text>
                <text class="extra-value">{{ formatDate(card.created_at) }}</text>
              </view>
              <view class="extra-item" style="flex: 4">
                <text class="extra-label">{{ useT('费率') }}</text>
                <text class="extra-value">{{ formatRate(card.redio) }}</text>
              </view>
            </view>
          </view>
        </template>

        <!-- 空数据状态 -->
        <view class="empty-card" v-if="bankCardList.length === 0 && userStore.isLoggedIn && !loading">
          <view class="empty-icon">
            <u-icon name="/static/empty.png" width="120rpx" height="120rpx" color="#ccc"></u-icon>
          </view>
          <view class="empty-text">{{ useT('暂无卡') }}</view>
          <view class="empty-tip">{{ useT('可前往购买U卡') }}</view>
        </view>
      </view>

      <!-- 资产明细列表 -->
      <view class="asset-details">
        <view class="detail-item" v-for="(item, index) in assetList" :key="index" @click="viewAssetDetail(item)">
          <view class="detail-left">
            <text class="detail-name">{{ item.name }}</text>
          </view>
          <view class="detail-center">
            <text class="detail-amount">{{ item.amount }}</text>
          </view>
          <view class="detail-right">
            <text class="detail-change" :class="{ positive: item.change > 0, negative: item.change < 0 }">{{ item.change > 0 ? '+' : '' }}{{ item.change }}%</text>
            <u-icon :name="item.change > 0 ? 'arrow-up' : 'arrow-down'" size="12" :color="item.change > 0 ? '#12C284' : '#ff4757'"></u-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 自定义 Tabbar -->
    <CustomTabbar :currentIndex="3" />
  </view>
</template>

<script setup>
import { getCardList } from '@/api/project.js';
import CustomTabbar from '@/components/CustomTabbar.vue';
import { useUserStore } from '@/stores/user';
import { useT } from '@/utils/i18n';
import { onShow } from '@dcloudio/uni-app';
import { nextTick, onMounted, reactive, ref } from 'vue';
const userStore = useUserStore();
// 响应式数据
const activeTab = ref('overview');
const scrollLeft = ref(0);
const bankCardList = ref([]);
const loading = ref(false);
const showAmount = ref(true); // 控制金额显示/隐藏

// 资产明细数据
const assetList = reactive([
  // {
  //   name: useT('钱包'),
  //   amount: '16,351.57',
  //   change: -3.7
  // },
  // {
  //   name: useT('理财'),
  //   amount: '16,351.57',
  //   change: 2.5
  // },
  // {
  //   name: useT('U卡'),
  //   amount: '16,351.57',
  //   change: 2.5
  // }
]);

// 获取银行卡列表
const loadCardList = async () => {
  // 判断登录状态
  if (!userStore.isLoggedIn) {
    bankCardList.value = [];
    return;
  }

  try {
    loading.value = true;
    const response = await getCardList();

    if (response && response.status === 200) {
      // 处理返回的数据，可能是数组或对象
      if (Array.isArray(response.data)) {
        bankCardList.value = response.data;
      } else if (response.data && Array.isArray(response.data.list)) {
        bankCardList.value = response.data.list;
      } else if (response.data) {
        // 如果返回的是单个对象，转为数组
        bankCardList.value = [response.data];
      } else {
        bankCardList.value = [];
      }
    } else {
      bankCardList.value = [];
    }
  } catch (error) {
    console.error('获取银行卡列表失败:', error);
    bankCardList.value = [];
  } finally {
    loading.value = false;
  }
};

onShow(() => {
  console.log('onShow');
  uni.hideTabBar();
  // 判断登录后获取银行卡列表
  loadCardList();
});

// 方法
const toggleAmountDisplay = () => {
  showAmount.value = !showAmount.value;
};

const switchTab = async (tab) => {
  activeTab.value = tab;
  console.log('切换到标签:', tab);

  // 计算滚动位置，让选中的标签居中显示
  await nextTick();
  const query = uni.createSelectorQuery();
  query.select(`#tab-${tab}`).boundingClientRect();
  query.select('.tabs-scroll').boundingClientRect();
  query.select('.tabs-scroll').scrollOffset();
  query.exec((res) => {
    if (res[0] && res[1]) {
      const tabItem = res[0];
      const scrollView = res[1];
      const scrollOffset = res[2];

      // 计算需要滚动的距离：让标签居中
      const scrollDistance = tabItem.left - scrollView.width / 2 + tabItem.width / 2 - scrollOffset.scrollLeft;
      scrollLeft.value = scrollOffset.scrollLeft + scrollDistance;
    }
  });
};

const handleRecharge = () => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    // 未登录，跳转到登录页面
    uni.navigateTo({
      url: '/pages/login/login'
    });
    return;
  }
  // 已实名认证 跳转到充值页面
  uni.navigateTo({
    url: '/pagesA/recharge/recharge'
  });
};

const handleWithdraw = () => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    // 未登录，跳转到登录页面
    uni.navigateTo({
      url: '/pages/login/login'
    });
    return;
  }
  if (userStore.userInfo.id_verify_status != 2) {
    // 未实名认证 跳转到实名认证页面
    uni.navigateTo({
      url: '/pagesA/identity/identity'
    });
    return;
  }
  if (userStore.userInfo.id_verify_status == 2) {
    // 已实名认证 跳转到提现页面
    uni.navigateTo({
      url: '/pagesA/withdraw/withdraw'
    });
    return;
  }
};

const handleRecord = () => {
  uni.navigateTo({
    url: '/pagesA/withdraw/record'
  });
};

const viewAssetDetail = (item) => {
  uni.showToast({
    title: `查看${item.name}详情`,
    icon: 'none'
  });
};

// 格式化卡号：每4位用空格隔开
const formatCardNumber = (cardNumber) => {
  if (!cardNumber) return '';
  // 移除所有空格和非数字字符
  const cleaned = String(cardNumber).replace(/\s+/g, '').replace(/\D/g, '');
  // 每4位插入一个空格
  return cleaned.replace(/(.{4})/g, '$1 ').trim();
};

// 获取卡片状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: useT('未激活'),
    1: useT('已激活'),
    2: useT('已冻结'),
    3: useT('已过期')
  };
  return statusMap[status] || useT('未知');
};

// 获取卡片状态样式类
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-inactive',
    1: 'status-active',
    2: 'status-frozen',
    3: 'status-expired'
  };
  return classMap[status] || '';
};

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '-';
  try {
    // 判断是否为时间戳（纯数字）
    let date;
    if (typeof timestamp === 'number' || /^\d+$/.test(String(timestamp))) {
      const ts = Number(timestamp);
      // 如果是10位时间戳（秒级），转换为毫秒
      if (ts.toString().length === 10) {
        date = new Date(ts * 1000);
      } else {
        // 13位时间戳（毫秒级）或其他长度，直接使用
        date = new Date(ts);
      }
    } else {
      // 字符串日期格式
      date = new Date(timestamp);
    }

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '-';
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch {
    return '-';
  }
};

// 格式化费率
const formatRate = (rate) => {
  if (rate === null || rate === undefined || rate === '') return '-';
  const numRate = Number(rate);
  if (isNaN(numRate)) return rate;
  // 如果是小数，保留2位小数；如果是整数，不显示小数
  if (numRate % 1 === 0) {
    return `${numRate}%`;
  }
  return `${numRate.toFixed(2)}%`;
};

// 生命周期
onMounted(() => {
  console.log('钱包页面加载完成');
});
</script>

<style lang="scss" scoped>
.wallet-container {
  min-height: 100vh;
  background-color: #ffffff;
  padding-bottom: 120rpx; /* 为 tabbar 留出空间 */
}

// 顶部标签切换
.tabs-scroll {
  width: 100%;
  white-space: nowrap;

  .tabs-container {
    display: inline-flex;
    align-items: center;
    padding: 20rpx 32rpx;
    white-space: nowrap;

    .tab-item {
      padding: 16rpx 24rpx;
      margin: 0 8rpx;
      position: relative;
      flex-shrink: 0;

      &.active {
        .tab-text {
          color: #12c284;
          font-weight: 600;
          background: #e8f8f3;
          padding: 12rpx 24rpx;
          border-radius: 20rpx;
          display: inline-block;
        }
      }

      .tab-text {
        font-size: 28rpx;
        color: #999;
        transition: all 0.3s ease;
        white-space: nowrap;
      }
    }
  }
}

.content {
  padding: 0 32rpx 40rpx;

  // 总资产估值区域
  .asset-section {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    margin: 32rpx 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .asset-left {
      flex: 1;

      .asset-header {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;

        .asset-title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          margin-right: 12rpx;
        }

        :deep(.u-icon) {
          padding: 8rpx;
          cursor: pointer;
          transition: opacity 0.3s ease;

          &:active {
            opacity: 0.6;
          }
        }
      }

      .asset-amount-wrapper {
        margin-top: 8rpx;

        .asset-amount {
          font-size: 48rpx;
          font-weight: 700;
          color: #333;
          line-height: 1.2;
          letter-spacing: 1rpx;
        }
      }

      .asset-tip {
        .tip-text {
          font-size: 26rpx;
          color: #999;
          line-height: 1.4;
        }
      }
    }

    .asset-right {
      .recharge-btn {
        padding: 20rpx 32rpx;
        background: linear-gradient(90deg, #4a90e2, #12c284);
        border-radius: 24rpx;
        position: relative;
        display: inline-block;

        &::before {
          content: '';
          position: absolute;
          top: 2rpx;
          left: 2rpx;
          right: 2rpx;
          bottom: 2rpx;
          background-color: #fff;
          border-radius: 22rpx;
        }

        .btn-text {
          color: #333366;
          font-size: 28rpx;
          font-weight: 600;
          position: relative;
          z-index: 1;
        }
      }
    }
  }

  // 操作按钮区域
  .action-section {
    background-color: #f8f9fa;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .action-item {
      display: flex;
      align-items: center;
      justify-content: center;
      flex: 1;
      padding: 16rpx 0;

      .action-icon {
        width: 48rpx;
        height: 48rpx;
        background-color: transparent;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16rpx;
      }

      .action-text {
        font-size: 28rpx;
        color: #666;
        font-weight: 500;
      }
    }

    .action-divider {
      width: 2rpx;
      height: 40rpx;
      background-color: #e0e0e0;
      margin: 0 24rpx;
    }
  }

  // 我的账户标题
  .account-title {
    margin-bottom: 24rpx;

    .title-text {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }
  }

  // 银行卡展示
  .card-section {
    margin-bottom: 32rpx;

    .bank-card {
      background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
      border-radius: 20rpx;
      padding: 40rpx 32rpx;
      position: relative;
      transition: all 0.3s ease;
      margin-bottom: 24rpx;

      &:last-child {
        margin-bottom: 0;
      }

      &.active {
        background: linear-gradient(135deg, #12c284 0%, #0ea86a 100%);
      }

      .card-chip {
        width: 71rpx;
        height: 50rpx;
        background-color: rgba(255, 255, 255, 0.2);
        border-radius: 6rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 24rpx;

        .chip-icon {
          width: 100%;
          height: 100%;
        }
      }

      .card-number {
        margin-bottom: 32rpx;

        .number-text {
          font-size: 34rpx;
          color: #fff;
          letter-spacing: 4rpx;
        }
      }

      .card-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 24rpx;

        .card-holder,
        .card-date {
          .holder-label,
          .date-label {
            font-size: 24rpx;
            color: rgba(255, 255, 255, 0.7);
            display: block;
            margin-bottom: 8rpx;
          }

          .holder-name,
          .date-value {
            font-size: 28rpx;
            color: #fff;
            font-weight: 500;
          }
        }
      }

      .card-extra-info {
        display: flex;
        justify-content: space-between;
        padding-top: 24rpx;
        border-top: 1rpx solid rgba(255, 255, 255, 0.2);

        .extra-item {
          flex: 6;
          display: flex;
          flex-direction: column;

          .extra-label {
            font-size: 22rpx;
            color: rgba(255, 255, 255, 0.7);
            margin-bottom: 8rpx;
          }

          .extra-value {
            font-size: 26rpx;
            color: #fff;
            font-weight: 500;

            &.status-active {
              color: #4ade80;
            }

            &.status-inactive {
              color: #fbbf24;
            }

            &.status-frozen {
              color: #f87171;
            }

            &.status-expired {
              color: #94a3b8;
            }
          }
        }
      }
    }

    // 空数据状态
    .empty-card {
      background: #f8f9fa;
      border-radius: 20rpx;
      padding: 80rpx 32rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .empty-icon {
        margin-bottom: 24rpx;
      }

      .empty-text {
        font-size: 32rpx;
        color: #666;
        font-weight: 500;
        margin-bottom: 12rpx;
      }

      .empty-tip {
        font-size: 26rpx;
        color: #999;
      }
    }
  }

  // 资产明细列表
  .asset-details {
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;

    .detail-item {
      display: flex;
      align-items: center;
      padding: 32rpx;
      border-bottom: 1rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .detail-left {
        flex: 1;

        .detail-name {
          font-size: 32rpx;
          color: #333;
          font-weight: 500;
        }
      }

      .detail-center {
        flex: 1;
        text-align: center;

        .detail-amount {
          font-size: 32rpx;
          color: #333;
          font-weight: 600;
        }
      }

      .detail-right {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .detail-change {
          font-size: 28rpx;
          font-weight: 500;
          margin-right: 8rpx;

          &.positive {
            color: #12c284;
          }

          &.negative {
            color: #ff4757;
          }
        }
      }
    }
  }
}
</style>
